package com.example.smartvillage;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.os.HandlerCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.smartvillage.adapters.HomeBannerAdapter;
import com.example.smartvillage.adapters.NewsListRecyclerAdapter;
import com.example.smartvillage.model.BannerBean;
import com.example.smartvillage.model.NewsData;
import com.example.smartvillage.utils.NewsDiffCallback;
import com.example.smartvillage.utils.Weather;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.zhpan.bannerview.BannerViewPager;
import com.zhpan.bannerview.constants.PageStyle;
import com.zhpan.bannerview.utils.BannerUtils;
import com.zhpan.indicator.enums.IndicatorSlideMode;
import com.zhpan.indicator.enums.IndicatorStyle;

import java.util.List;

public class HomeFragment extends Fragment implements NewsListRecyclerAdapter.ItemClickListener{

    private static final String TAG = "主页";

    BottomNavigationView bottomNav;

    MainViewModel model;
    Handler mainThreadHandler = HandlerCompat.createAsync(Looper.getMainLooper());

    SwipeRefreshLayout swipeRefreshLayout;

    BannerViewPager<BannerBean> bannerViewPager;
    TextView tv_weather,tv_notice;

    RecyclerView newsRecyclerView;
    NewsListRecyclerAdapter newsListRecyclerAdapter;

    public HomeFragment() {
        super(R.layout.fragment_home);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requireActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        model = new ViewModelProvider(requireActivity()).get(MainViewModel.class);

        newsListRecyclerAdapter = new NewsListRecyclerAdapter();
        newsListRecyclerAdapter.setClickListener(this);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container,false);

        //进入主页显示底部导航栏与应用栏
        bottomNav = requireActivity().findViewById(R.id.bottom_nav);
        bottomNav.setVisibility(View.VISIBLE);
        ((AppCompatActivity)requireActivity()).getSupportActionBar().show();

        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
        bannerViewPager = view.findViewById(R.id.banner_view);
        tv_weather = view.findViewById(R.id.weather_tab);
        tv_notice = view.findViewById(R.id.announcement_tab);
        newsRecyclerView = view.findViewById(R.id.rv_news);

        //滑动刷新
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        swipeRefreshLayout.setOnRefreshListener(onRefreshListener);

        //头图初始化
        initBannerViewPager();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        newsRecyclerView.setLayoutManager(linearLayoutManager);
        newsRecyclerView.setAdapter(newsListRecyclerAdapter);

        //更新新闻视图
        model.getNewsData().observe(getViewLifecycleOwner(), newDataDTOS -> {
            Log.d(TAG, "新闻数据改变");
            List<NewsData.ResultDTO.DataDTO> mDataDTOS = newsListRecyclerAdapter.getDataDTOs();//旧数据
            DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new NewsDiffCallback(mDataDTOS, newDataDTOS), false);
            diffResult.dispatchUpdatesTo(newsListRecyclerAdapter);

            newsListRecyclerAdapter.setDataDTOs(newDataDTOS);
        });
        //更新天气视图
        model.getWeatherData().observe(getViewLifecycleOwner(), weatherData -> {
            Log.d(TAG, "天气数据改变");
            if (weatherData.getError_code() == 0) {
                tv_weather.setText(getString(R.string.weather_info,
                        model.getWeatherData().getValue().getResult().getRealtime().getInfo(),
                        model.getWeatherData().getValue().getResult().getRealtime().getTemperature()));
                tv_weather.setCompoundDrawablesWithIntrinsicBounds(
                        Weather.getWeatherIcon(model.getWeatherData().getValue().getResult().getRealtime().getWid()), 0, 0, 0);
            }
            else {
                tv_weather.setText("天气加载失败");
            }
        });
        //更新公告视图
        model.getNoticeList().observe(getViewLifecycleOwner(), notices -> {
            tv_notice.setText(getString(R.string.notice_info, notices.get(0).toString()));
        });

        return view;

    }

    @Override
    public void onItemClick(View view, int position, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    //刷新监听
    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            model.loadNewsData();
            Log.d(TAG, "加载新的新闻数据");
            mainThreadHandler.post(() -> {
                swipeRefreshLayout.setRefreshing(false);
                Log.d(TAG, "主页刷新完成");
            });
        }
    };

    void initBannerViewPager() {
        bannerViewPager.setAdapter(new HomeBannerAdapter())
                .setLifecycleRegistry(getLifecycle())
                .setRoundCorner(16)
                .setPageStyle(PageStyle.MULTI_PAGE_SCALE)
                .setIndicatorStyle(IndicatorStyle.DASH)
                .setIndicatorHeight(BannerUtils.dp2px(4))
                .setIndicatorSliderWidth(BannerUtils.dp2px(16))
                .setIndicatorSliderColor(getResources().getColor(R.color.lite_gray), getResources().getColor(R.color.colorPrimary))
                .setIndicatorSlideMode(IndicatorSlideMode.SMOOTH)
                .setScrollDuration(500)
                .setInterval(5000)
                .create(model.getListBannerBean().getValue());
    }
}